<template>
  <div class="diy">
    <div class="text" contenteditable="true" ref="text" @input="changeContent" @blur="getblur">
    </div>
    <div class="tag">
      <div>
        <span class="num">{{num}}/200</span>
        <el-tag @click="name?null:setInvit(1)" :class="{'disabled':name}"># 求职者姓名 #</el-tag>
        <el-tag @click="company?null:setInvit(2)" :class="{'disabled':company}"># 公司名称 #</el-tag>
        <el-tag @click="job?null:setInvit(3)" :class="{'disabled':job}"># 职位名称 #</el-tag>
      </div>
      <div class="saveBox">
        <el-button type="primary" plain @click="handleClose">取消</el-button>
        <el-button type="primary" @click="addTem">保存</el-button>
      </div>
    </div>
  </div>
</template>

<script>
import { inviteUpdate, editInfo, inviteSave } from '../../../../api/commonWords'
export default {
  name: 'diy',
  props: ['customize', 'flag'],
  data () {
    return {
      reg: /(#(\S*)#)|(\S*)/g,
      job: false,
      company: false,
      name: false,
      edit: true,
      num: 0,
      sel: null,
      range: null,
      typeChinese: false
    }
  },
  mounted () {
    // 监听开始输入中文
    this.$refs.text.addEventListener('compositionstart', () => {
      this.typeChinese = true;
    })
    // 监听结束输入中文
    this.$refs.text.addEventListener('compositionend', () => {
      if (!this.edit) {
        let content = this.$refs.text.innerText;
        content = content.slice(0, 200);
        this.$refs.text.innerHTML = '';
        this.init(content)
        this.num = content.length;
        this.set_focus(this.$refs.text)
      }
      this.typeChinese = false;
    })
  },
  watch: {
    // 修改时获取自定义模板
    'flag': function () {
      if (this.flag && this.customize) {
        this.init(this.customize.invitContent);
        this.set_focus(this.$refs.text)
      } else if (this.flag) {
        this.$refs.text.innerHTML = '';
        this.name = false;
        this.company = false;
        this.job = false;
        this.num = 0;
        this.edit = true;
        this.set_focus(this.$refs.text)
      }
    },
    // 监听字数
    'num': function () {
      if (this.num >= 200) {
        this.edit = false;
        this.changeContent();
      } else {
        this.edit = true;
      }
    }
  },
  methods: {
    // 设置光标位置
    set_focus (e) {
      if (window.getSelection) {
        e.focus();
        let range = window.getSelection();
        range.selectAllChildren(e);
        range.collapseToEnd();
      } else {
        let range = document.selection.createRange();
        range.moveToElementText(e);
        range.collapse(false)
        range.select();
      }
    },
    // 编辑模板
    changeContent () {
      let content = this.$refs.text.innerText;
      if (!this.edit && !this.typeChinese) {
        let content = this.$refs.text.innerText;
        content = content.slice(0, 200);
        this.$refs.text.innerHTML = '';
        this.init(content)
        this.num = content.length;
        this.set_focus(this.$refs.text)
        return
      }
      if (content.includes('#求职者姓名#')) {
        this.name = true;
      } else {
        this.name = false;
      }
      if (content.includes('#公司名称#')) {
        this.company = true;
      } else {
        this.company = false;
      }
      if (content.includes('#职位名称#')) {
        this.job = true;
      } else {
        this.job = false;
      }
      this.num = content.length;
    },
    // 初始化自定义模板
    init (text) {
      console.log(text);
      let ary = text.match(this.reg)
      ary.forEach(i => {
        if (i.includes('#')) {
          if (i.includes('求职者姓名')) {
            this.name = true;
          }
          if (i.includes('公司名称')) {
            this.company = true;
          }
          if (i.includes('职位名称')) {
            this.job = true;
          }
          let text = document.createElement('span');
          text.style.color = '#0093FF'
          text.contentEditable = false;
          text.innerHTML = ' ' + i;
          this.$refs.text.appendChild(text);
          console.log(i);
        } else {
          console.log(i);
          this.$refs.text.innerHTML += i;
        }
        this.num = ary.join('').length;
      });
    },
    // 获取光标位置
    getblur () {
      this.sel = window.getSelection();
      this.range = this.sel.getRangeAt(0);
      this.range.deleteContents();
    },
    // 添加标签
    setInvit (val) {
      if (!this.edit) {
        return
      }
      let text = document.createElement('span');
      text.style.color = '#0093FF'
      switch (val) {
        case 1:
          text.innerHTML = ' #求职者姓名#'
          this.name = true;
          break;
        case 2:
          text.innerHTML = ' #公司名称#'
          this.company = true;
          break;
        case 3:
          text.innerHTML = ' #职位名称#'
          this.job = true;
          break;
      }
      text.contentEditable = false;
      // this.sel = window.getSelection()
      // this.range = this.sel.getRangeAt(0)
      this.range.setStart(this.range.endContainer, this.range.endOffset) // 设置开始插入位置
      this.range.insertNode(text) // 插入元素，node节点
      this.range.setEnd(this.range.endContainer, this.range.endOffset) // 设置结束位置
      // selection.selectAllChildren(this.$refs.text) //选择容器
      // selection.collapseToEnd() // 移动光标到最后
      // this.$refs.text.appendChild(text);
      this.changeContent();
      this.set_focus(this.$refs.text)
    },
    // 关闭编辑自定义模板
    handleClose () {
      this.$refs.text.innerHTML = '';
      this.name = false;
      this.company = false;
      this.job = false;
      this.num = 0;
      this.$emit('close', false)
    },
    // 保存自定义模板
    addTem () {
      let text = this.$refs.text.innerText
      console.log(text);
      if (text) {
        if (this.customize) {
          let query = {
            id: this.customize.id,
            title: this.customize.title,
            invitContent: text
          }
          inviteUpdate(query).then(res => {
            if (res.success) {
              this.handleClose();
              this.$message.success('修改成功！')
            } else {
              this.$message.error(res.msg)
            }
          })
        } else {
          let query = {
            title: '自定义模板',
            invitContent: text
          }
          inviteSave(query).then(res => {
            if (res.success) {
              this.handleClose();
              this.$message.success('添加成功！')
            } else {
              this.$message.error(res.msg)
            }
          })
        }

      } else {
        this.$message.error(`请输入模板内容`)
      }
    }
  }
}
</script>

<style lang="css" scoped>
.diy {
    width: 100%;
}
.diy .el-button {
    font-size: 12px;
    font-family: Source Han Sans CN;
    font-weight: 400;
    line-height: 0;
    width: 94px;
    height: 24px;
    opacity: 1;
}
.text {
    width: 1112px;
    height: 114px;
    font-size: 14px;
    background: rgba(248, 248, 248, 1);
    opacity: 1;
}
.tag {
    margin-bottom: 20px;
    margin-top: 16px;
    display: flex;
    justify-content: space-between;
}
.el-tag {
    margin-left: 24px;
    cursor: pointer;
}
.disabled {
    color: #555555;
    border: 1px solid rgba(204, 204, 204, 1);
}
.num {
    display: inline-block;
    margin-right: 48px;
    width: 37px;
    height: 15px;
    font-size: 14px;
    font-family: Source Han Sans CN;
    font-weight: 400;
    line-height: 16px;
    color: rgba(117, 117, 117, 1);
    opacity: 1;
}
</style>